<script setup lang="ts">
import { generateKey } from '@/api/llm/api'
import useDictStore from '@/store/modules/dict'
import { ModalShowType, GenericResult } from '@/types/common'
import { ElButton, ElForm, ElFormItem, ElInput, FormInstance, ElMessageBox, ElMessage } from 'element-plus'
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Refresh, DocumentCopy, Warning } from '@element-plus/icons-vue'

const router = useRouter()
const showGenerateKeyDialog = ref(false)
const newApiKey = ref('')

const props = defineProps<{
  modalShow: ModalShowType
  apiName: string
  apiUrl: string
  apiKey: string
  modelName: string
  modelType: string
  tokens: string
  useTimeBegin: string
  useTimeEnd: string
  onSearch?: () => Promise<void>
  modelApiId: string
}>()

const emit = defineEmits<{
  (e: 'update:modalShow', type: ModalShowType): void
  (e: 'update:apiKey', key: string): void
}>()

const modalShow = computed({
  get() {
    return props.modalShow
  },
  set(value) {
    emit('update:modalShow', value)
  },
})
const dictStore = useDictStore()
const { api_type } = dictStore.getDicts('api_type')

function onClose() {
  if (props.modalShow === ModalShowType.Edit) {
    props.onSearch()
  }
  modalShow.value = ModalShowType.Hide
}

const handleGenerateKey = async () => {
  try {
    const res = await generateKey(props.modelApiId) as any
    if (res.code === 200 && res.data) {
      const newKey = res.data
      newApiKey.value = newKey
      emit('update:apiKey', newKey)
      ElMessage.success('密钥生成成功')
      // 调用父组件的 onSearch 方法刷新列表
      props.onSearch?.()
    }
  } catch (error) {
    console.error('生成密钥失败:', error)
    // ElMessage.error('生成密钥失败')
  }
}

const handleCopyKey = () => {
  navigator.clipboard.writeText(newApiKey.value)
  ElMessage.success('复制成功')
}

const handleConfirmGenerate = async () => {
  try {
    await ElMessageBox.confirm('请确认是否重新生成密钥？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await handleGenerateKey()
  } catch (error) {
    console.error('生成密钥失败:', error)
  }
}

// 监听对话框显示状态
watch(showGenerateKeyDialog, (newVal) => {
  if (newVal) {
    newApiKey.value = props.apiKey
  }
})

const maskApiKey = computed(() => {
  if (!props.apiKey) return '-'
  const key = props.apiKey
  if (key.length <= 10) return key
  return `${key.slice(0, 5)}${'*'.repeat(key.length - 10)}${key.slice(-5)}`
})
</script>

<template>
  <el-drawer
    :close-on-click-modal="false"
    title="接口详情"
    class="common-dialog"
    :model-value="modalShow !== ModalShowType.Hide"
    :before-close="onClose"
    size="50%"
  >
    <section-info>
      <template #title>模型接口</template>
      <table>
        <colgroup>
          <col class="w-[150px]" />
        </colgroup>
        <tr>
          <td>接口名称:</td>
          <td>
            <template v-if="props.apiName">
              <copy-text :content="props.apiName" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
        <br />
        <tr>
          <td>接口地址:</td>
          <td>
            <template v-if="props.apiUrl">
              <copy-text :content="props.apiUrl" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
        <br />
        <tr>
          <td>接口密钥:</td>
          <td>
            <div class="flex items-center gap-2">
              {{ maskApiKey }}
              <el-icon @click="showGenerateKeyDialog = true" class="cursor-pointer text-[20px] text-primary">
                <Refresh />
              </el-icon>
            </div>
          </td>
        </tr>
        <br />
        <tr>
          <td>模型名称:</td>
          <td>
            <template v-if="props.modelName">
              <copy-text :content="props.modelName" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
        <br />
        <tr>
          <td>模型类别:</td>
          <td>
            <template v-if="props.modelType">
              <copy-text :content="props.modelType" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
        <br />
        <tr>
          <td>消耗tokens:</td>
          <td>
            <template v-if="props.tokens">
              <copy-text :content="props.tokens" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
        <br />
        <tr>
          <td>开始使用期限:</td>
          <td>
            <template v-if="props.useTimeBegin">
              <copy-text :content="props.useTimeBegin" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
        <br />
        <tr>
          <td>结束使用期限:</td>
          <td>
            <template v-if="props.useTimeEnd">
              <copy-text :content="props.useTimeEnd" />
            </template>
            <template v-else>-</template>
          </td>
        </tr>
      </table>
    </section-info>
    <template #footer>
      <el-button v-if="modalShow === ModalShowType.View" @click="modalShow = ModalShowType.Hide">
        关闭
      </el-button>
    </template>
  </el-drawer>
  <el-dialog
    v-model="showGenerateKeyDialog"
    title="生成密钥"
    width="500px"
    :close-on-click-modal="false"
    style="min-height: 200px;"
  >
    <div class="flex flex-col gap-6">
      <div class="flex items-center gap-4 w-full">
        <el-input v-model="newApiKey" readonly class="flex-1" />
        <el-icon @click="handleConfirmGenerate" class="cursor-pointer text-[20px] text-primary">
          <Refresh />
        </el-icon>
        <el-icon @click="handleCopyKey" class="cursor-pointer text-[20px]">
          <DocumentCopy />
        </el-icon>
      </div>
      <div class="flex items-start gap-3">
        <el-icon class="text-warning text-[16px] mt-[2px]"><Warning /></el-icon>
        <p class="text-gray-500 text-[14px]">
          请妥善保管密钥信息，重新生成密钥操作将导致原密钥永久失效，且关闭当前界面后系统将不再提供完整密钥展示功能
        </p>
      </div>
    </div>
  </el-dialog>
</template>
